package com.medvalley.tcm.controller.admin.service;

import com.google.common.collect.Lists;
import com.medvalley.tcm.base.BusinessException;
import com.medvalley.tcm.base.Constants;
import com.medvalley.tcm.controller.admin.vo.inputvo.OrgInputVo;
import com.medvalley.tcm.controller.admin.vo.inputvo.SearchOrgInputVo;
import com.medvalley.tcm.controller.admin.vo.outputvo.OrgOutputVo;
import com.medvalley.tcm.controller.admin.vo.outputvo.PageDataOutputVo;
import com.medvalley.tcm.dao.OrgDao;
import com.medvalley.tcm.domain.Organization;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author linsong
 * @date 2019/6/20 11:27
 **/
@Service
public class OrgService {

    @Autowired
    private OrgDao orgDao;

    public PageDataOutputVo<OrgOutputVo> listOrg(SearchOrgInputVo searchOrgInputVo) {
        PageDataOutputVo<OrgOutputVo> outputVo = new PageDataOutputVo<>();
        int pageNo = searchOrgInputVo.getPageNo();
        int pageSize = searchOrgInputVo.getPageSize();
        List<OrgOutputVo> orgOutputVoList = Lists.newArrayList();
        outputVo.setPageNo(pageNo);
        outputVo.setPageSize(pageSize);
        pageNo = pageNo - 1 < 0 ? 0 : pageNo - 1;
        Pageable pageable = PageRequest.of(pageNo, pageSize, Sort.Direction.DESC, "id");
        Specification<Organization> specification = new Specification<Organization>() {

            @Override
            public Predicate toPredicate(Root<Organization> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                // 创建时间-  开始
                if (!StringUtils.isEmpty(searchOrgInputVo.getBeginDate())) {
                    list.add(criteriaBuilder.greaterThan(root.get("createTime").as(String.class), searchOrgInputVo.getBeginDate()));
                }
                // 创建时间-  结束
                if (!StringUtils.isEmpty(searchOrgInputVo.getEndDate())) {
                    list.add(criteriaBuilder.lessThan(root.get("createTime").as(String.class), searchOrgInputVo.getEndDate()));
                }
                String phone = searchOrgInputVo.getPhone();
                if (!StringUtils.isEmpty(phone)) {
                    list.add(criteriaBuilder.equal(root.get("phone").as(String.class), phone));
                }
                String leaderName = searchOrgInputVo.getLeaderName();
                if (!StringUtils.isEmpty(leaderName)) {
                    list.add(criteriaBuilder.like(root.get("leader").as(String.class), leaderName + "%"));
                }
                String address = searchOrgInputVo.getOrgAddress();
                if (!StringUtils.isEmpty(address)) {
                    list.add(criteriaBuilder.like(root.get("address").as(String.class), address + "%"));
                }
                String orgName = searchOrgInputVo.getOrgName();
                if (!StringUtils.isEmpty(orgName)) {
                    list.add(criteriaBuilder.like(root.get("name").as(String.class), orgName + "%"));
                }

                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };
        Page<Organization> pageData = orgDao.findAll(specification, pageable);
        if (pageData.hasContent()) {
            List<Organization> organizationList = pageData.getContent();
            for (Organization o : organizationList) {
                OrgOutputVo orgOutputVo = new OrgOutputVo();
                orgOutputVo.setId(o.getId());
                orgOutputVo.setOrgName(o.getName());
                orgOutputVo.setAddress(o.getAddress());
                orgOutputVo.setLeader(o.getLeader());
                orgOutputVo.setLeaderPhone(o.getPhone());
                orgOutputVo.setCreateTime(DateFormatUtils.format(o.getCreateTime(), Constants.YYYY_MM_DD_HH_MM_SS));
                orgOutputVoList.add(orgOutputVo);
            }
        }
        outputVo.setPageData(orgOutputVoList);
        outputVo.setTotalElement(pageData.getTotalElements());
        outputVo.setTotalPageCount(pageData.getTotalPages());

        return outputVo;
    }

    public void deleteOrg(int id) {
        orgDao.deleteById(id);
    }

    public OrgOutputVo orgDetail(int id) {
        Organization organization = orgDao.findById(id).orElseThrow(() -> new BusinessException("无此机构"));
        OrgOutputVo outputVo = new OrgOutputVo();
        outputVo.setId(organization.getId());
        outputVo.setOrgName(organization.getName());
        outputVo.setLeader(organization.getLeader());
        outputVo.setLeaderPhone(organization.getPhone());
        outputVo.setAddress(organization.getAddress());
        outputVo.setCreateTime(DateFormatUtils.format(organization.getCreateTime(), Constants.YYYY_MM_DD_HH_MM_SS));
        return outputVo;
    }

    public void updateOrg(OrgInputVo orgInputVo) {
        Organization organization;
        if (orgInputVo.getId() == 0) {
            organization = new Organization();
        }else {
            organization = orgDao.findById(orgInputVo.getId()).orElseThrow(() -> new BusinessException("无此机构"));
        }
        organization.setName(orgInputVo.getOrgName());
        organization.setAddress(orgInputVo.getAddress());
        organization.setLeader(orgInputVo.getLeader());
        organization.setPhone(orgInputVo.getLeaderPhone());
        orgDao.save(organization);
    }
}
